package cn.vcjf.washcar.api.order.service.impl;

import cn.vcjf.washcar.api.order.entity.WashCarOrder;
import cn.vcjf.washcar.api.order.mapper.WashCarOrderMapper;
import cn.vcjf.washcar.api.order.service.WashCarOrderService;
import cn.vcjf.washcar.api.service.entity.ServerInfo;
import cn.vcjf.washcar.api.service.entity.ServiceTime;
import cn.vcjf.washcar.api.service.service.ServerInfoService;
import cn.vcjf.washcar.api.service.service.ServiceTimeService;
import cn.vcjf.washcar.api.user.entity.User;
import cn.vcjf.washcar.api.user.service.UserService;
import cn.vcjf.washcar.common.exception.ServiceException;
import cn.vcjf.washcar.common.util.DateUtils;
import cn.vcjf.washcar.common.util.SysParamUtil;
import cn.vcjf.washcar.common.web.TableResult;
import cn.vcjf.washcar.common.wxpay.AbstractWxpayService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 洗车订单表 服务实现类
 * </p>
 *
 * @author zhengzihang
 * @since 2018-07-20
 */
@Service("washCarOrderService")
public class WashCarOrderServiceImpl extends ServiceImpl<WashCarOrderMapper, WashCarOrder> implements WashCarOrderService {

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Value("${server.domain.name}")
	private String domain;
	@Value("${wxpay.notifyUrl}")
	private String notifyUrl;
	@Resource
	private UserService userService;
	@Resource
	private ServerInfoService serverInfoService;
	@Resource
	private ServiceTimeService serviceTimeService;

	@Override
	public TableResult addWashCarOrder(HttpServletRequest request, WashCarOrder washCarOrder) throws ParseException {

		EntityWrapper<User> wrapper = new EntityWrapper<User>();

		if (washCarOrder.getUserId() == null) {
			throw new ServiceException("UserId为空");
		}
		wrapper.eq("id", washCarOrder.getUserId());
		User user = userService.selectOne(wrapper);
		if (user == null) {
			throw new ServiceException("UserId不存在");
		}
		//服务价格信息
		ServerInfo serverInfo = serverInfoService.selectById(washCarOrder.getServerType());
		washCarOrder.setMoney(serverInfo.getPrice());
		//优惠价格
		washCarOrder.setDiscounts(serverInfo.getDiscounts());
		washCarOrder.preInsert();
		washCarOrder.setStatus(WashCarOrder.ORDER_UNDING);


		ServiceTime serviceTime = serviceTimeService.selectById(washCarOrder.getWashTime());

		Integer date = serviceTime.getDate();

		Date startTime = DateUtils.parseDate(serviceTime.getStartTime(), "HH:mm");
		Long startWashTime=startTime.getTime()+date*24L*60*60*1000;
		startTime=new Date(startWashTime);
		String formatStartTime = DateUtils.formatDate(startTime, "HH:mm");

		Date endTime = DateUtils.parseDate(serviceTime.getEndTime(), "HH:mm");
		Long endWashTime=endTime.getTime()+date*24L*60*60*1000;
		endTime=new Date(endWashTime);
		String formatEndTime = DateUtils.formatDate(endTime, "HH:mm");
		String dateNow=DateUtils.getDate("yyyy-MM-dd");
		try {
			startTime = DateUtils.parseDate(dateNow+" "+formatStartTime,"yyyy-MM-dd HH:mm");
			endTime = DateUtils.parseDate(dateNow+" "+formatEndTime,"yyyy-MM-dd HH:mm");
		} catch (ParseException e) {
			e.printStackTrace();
		}

		washCarOrder.setWashStartTime(startTime);
		washCarOrder.setWashEndTime(endTime);
		boolean b = this.insert(washCarOrder);

		AbstractWxpayService wxpayService = new AbstractWxpayService() {
			@Override
			public String getNotifyOrderUrl() {

				return domain+notifyUrl;
			}
		};

		BigDecimal money = null;
		//交易金额=价格-优惠价格
		if(washCarOrder.getDiscounts()!=null){
			money = washCarOrder.getMoney().subtract(washCarOrder.getDiscounts());
		}else {
		    money = washCarOrder.getMoney();
		}
		money = money.multiply(new BigDecimal("100")).setScale(0,BigDecimal.ROUND_HALF_UP);
		String ip=AbstractWxpayService.getIpAddr(request);
		if(SysParamUtil.isTestModel()){
			ip="192.168.0.106";
		}
		TableResult result = wxpayService.doWxUnifiedOrder(user.getOpenId(), serverInfo.getServerName()+"消费", washCarOrder.getOrderNo(), money.toString(), ip);
		if (result.OK()){
			washCarOrder.setStatus(WashCarOrder.ORDER_UNDING_SUCCESS);
			washCarOrder.setPayData(JSONObject.toJSONString(result.getData()));
		}else {
			washCarOrder.setStatus(WashCarOrder.ORDER_UNDING_FAIL);
			washCarOrder.setPayData(result.getMsg());
		}
		b = this.updateById(washCarOrder);
		result.setCode(b);
		return result;
	}
	@Scheduled(cron = "0 0 17 * * ?")//每分钟都执行
//	@Scheduled(cron = "0 */1 * * * ?")//每分钟都执行
	@Override
	public void updateCheckOrder(){

		logger.info("定时自动完成订单-------------开始-----");
		EntityWrapper<WashCarOrder> wrapper = new EntityWrapper<WashCarOrder>();

		wrapper.eq("status",WashCarOrder.ORDER_PAY_OK);
		wrapper.ne("serviceStatus",WashCarOrder.ORDER_SERVERED);
		wrapper.lt("payTime",DateUtils.subDate(-3));
		wrapper.lt("updateTime",DateUtils.subDate(-3));

		List<WashCarOrder> washCarOrders = baseMapper.selectList(wrapper);
		logger.info("定时自动完成订单共{}条--------{}",washCarOrders.size(),washCarOrders);
		if(washCarOrders!= null&&!washCarOrders.isEmpty()) {
			for (WashCarOrder order : washCarOrders) {
				order.setServiceStatus(WashCarOrder.ORDER_SERVERED);
				order.preUpdate();
				baseMapper.updateWashOrderStatus(order);
			}
		}
	}

	@Override
	public void updateWashOrderStatus(WashCarOrder order, Integer orderStatus, String res, String pOrderNo) {
		order.setId(order.getId());
		order.setStatus(orderStatus);
		order.setpOrderNo(pOrderNo);
		order.setpResult(res);
		order.setServiceStatus(WashCarOrder.ORDER_WATI_SERVER);
		if(WashCarOrder.ORDER_PAY_OK==orderStatus){
			order.setPayTime(new Date());
		}

		baseMapper.updateWashOrderStatus(order);
	}

	@Override
	public WashCarOrder selectWashCarOrderOne(EntityWrapper<WashCarOrder> wrapper) {
		return baseMapper.selectWashCarOrderOne(wrapper);
	}
}
